<?php


namespace app\task\command\coupon;


use app\model\BaseSupplier;
use app\model\CouponOrder;
use app\model\GoodsNotify;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class Jiaofei100 extends Command
{
    /**
     * 配置指令.
     */
    protected function configure()
    {
        $this->setName('jiaofei100:createOrder')
            ->setDescription('Create jiaofei coupon order');
    }

    /**
     * 指令执行 php think jiaofei100:createOrder
     * @param Input $input
     * @param Output $output
     * @return bool|int|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function execute(Input $input, Output $output)
    {
        $start = date('Y-m-d H:i:s');
        echo '缴费100开始下单' . PHP_EOL;

        $lockKey = 'jiaofei_order_lock_key';
        $lockVal = cache($lockKey);
        if ($lockVal) {
            echo '还在处理呢' . PHP_EOL;

            return true;
        }

        cache($lockKey, 1, 120);

        $baseSupplier = BaseSupplier::where(['code' => 'jiaofei100'])
            ->whereNull('deleted_at')
            ->find();

        if (empty($baseSupplier)) {
            echo '缴费接口配置有误' . PHP_EOL;
            cache($lockKey, null);

            return false;
        }

        $couponOrderModel = CouponOrder::where([
            'status' => CouponOrder::C_STATUS_NO_SUBMIT,
            'pay_status' => CouponOrder::C_PAY_STATUS_YES,
            'supplier_id' => $baseSupplier['id']
            ])
            ->whereNull('deleted_at')
            ->with(['goodsCart'])
            ->limit(100)
            ->select()
            ->toArray();
        if (empty($couponOrderModel)) {
            echo '缴费100下单结束 没有可处理的订单' . PHP_EOL;
            cache($lockKey, null);

            return false;
        }


        $done = 0;
        $jiaofeiModel = new \api\coupon\Jiaofei100($baseSupplier);
        foreach ($couponOrderModel as $model) {
            $goodsCart = $model['goodsCart'] ?? '';
            if (empty($goodsCart)) {
                continue;
            }
            $data = [
                'order_id' => $model['order_id'],
                'sku_id' => $goodsCart['sku_id'],
                'account' => $goodsCart['account'],
                'quantity' => $goodsCart['quantity'],
            ];

            if ('视频接口' == $goodsCart['api_name']) {
                $ret = $jiaofeiModel->createVideo($data);
            } else {
                // 游戏接口
                $tradeType = 2 == $goodsCart['sku_type'] ?  23 : 45; // 商品类型
                $data['trade_type'] = $tradeType;
                $data['market_price'] = $goodsCart['market_price'];
                $data['api_ip'] = $goodsCart['api_ip'];
                $ret = $jiaofeiModel->createCard($data);
            }

            GoodsNotify::addGoods(json_encode($ret, JSON_UNESCAPED_UNICODE), $data, $model['order_id']);

            if (!isset($ret['Code'])) {
                continue;
            }

            $update = [];
            if (isset($ret['ReturnOrderID'])) {
                $update['supplier_order_sn'] = sprintf("%.0f", $ret['ReturnOrderID']);
            }


            if ('10018' == $ret['Code']) {
                ++$done;
                $update['status'] = CouponOrder::C_STATUS_SUBMIT;
                $update['status_msg'] = '';
            } else {
                $update['status'] = CouponOrder::C_STATUS_SUBMIT_FAIL;
                $update['refund_status'] = CouponOrder::C_REFUND_STATUS_ING;
                $update['status_msg'] = $ret['Msg'] ?? '下单失败';
            }

            $flag = CouponOrder::update($update, ['id' => $model['id']]);

            if (!$flag) {
                echo '更新异常：' . json_encode($update) . PHP_EOL;
            }
        }

        if (isProd()) {
            $balance = $jiaofeiModel->queryAmount();
            if ($balance !== false) {
                // 更新余额
                $baseSupplier->balance = $balance;
                $baseSupplier->save();
            }
        }


        cache($lockKey, null);

        echo '缴费100下单结束。成功下了 ' . $done . ' 单 ' . $start . '--' . date('Y-m-d H:i:s') . PHP_EOL;
    }
}